//
//  JKBaseThemeViewController.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/13.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit
import MJRefresh
import Kingfisher

class JKBaseThemeViewController: JKBaseViewController {
    
    // MARK: - 公共属性
    
    /** 主题模型 */
    var themeModel: JKThemeModel? {
        
        didSet{
            
            navTitle = themeModel?.name
            
            if stories.count > 0 {
                
                tableViewPlain.backgroundColor = view.backgroundColor
                
                stories.removeAll()
                tableViewPlain.reloadData()
                
                refreshView.frame = CGRect(x: (JKScreenW - calculateTitleWidth()) * 0.5 - 32, y: JKStatusBarHeight + 10, width: 24, height: 24)
                
                for subV in self.tableViewPlain.tableHeaderView!.subviews {
                    
                    if subV is UIImageView {
                        
                        if subV.tag == 100 { continue }
                        subV.removeFromSuperview()
                    }
                }
            }
            
            UIView.animate(withDuration: 0.5) {
                
                self.topImageView.alpha = 0
            }
        }
    }
    
    // MARK: - 私有属性
    
    /** 顶部图片高度 */
    private let topImageH: CGFloat = JKScreenW * 0.38
    
    /** story模型数组 */
    private var stories = [JKNewsListModel]()
    
    /** 主编模型数组 */
    private var editors = [JKThemeEditorModel]()
    
    /** 主题内容模型 */
    private var contentModel: JKThemeContentModel?
    
    /** 顶部图片 容器view */
    private lazy var topImageContainerViewView: UIImageView = {
        
        let topImageContainerViewView = UIImageView(frame:CGRectMake(0, -(self.topImageH - JKNavBarHeight) * 0.5, JKScreenW, self.topImageH))
        topImageContainerViewView.image = UIImage(named: "Home_Image_Mask_Plus")
        view.insertSubview(topImageContainerViewView, belowSubview: contentView)
        
        return topImageContainerViewView
    }()
    
    /** 顶部图片 上面的模糊图片 */
    private lazy var topImageCoverView: UIImageView = {
        
        let topImageCoverView = UIImageView(frame: topImageContainerViewView.bounds)
        
        let maskImageView = UIImageView(frame: topImageContainerViewView.bounds)
        maskImageView.image = UIImage(named: "Home_Image_Mask_Plus")
        topImageCoverView.addSubview(maskImageView)
        
        return topImageCoverView
    }()
    
    /** 顶部的图片 */
    private lazy var topImageView: UIImageView = {
        
        let topImageView = UIImageView(frame: topImageContainerViewView.bounds)
        topImageView.alpha = 0
        topImageContainerViewView.insertSubview(topImageView, at: 0)
        
        topImageView.addSubview(topImageCoverView)
        
        return topImageView
    }()
    
    /** 刷新控件 */
    private lazy var refreshView: JKHomeRefreshProgressView = {
        
        let refreshView = JKHomeRefreshProgressView()
        refreshView.frame = CGRect(x: (JKScreenW - calculateTitleWidth()) * 0.5 - 32, y: JKStatusBarHeight + 10, width: 24, height: 24)
        
        refreshView.backgroundColor = UIColor.clear
        
        view.addSubview(refreshView)
        
        return refreshView
    }()
    
    /** tableHeaderView */
    private var headerContainerView: UIView?
    
    /** tableHeaderView上的label */
    private var headerLabel: UILabel?
    
    // MARK:- 生命周期方法
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        
    }

    // MARK: - 初始化
    
    override func viewDidLoad() {
        
        contentViewUseFrame = true
        
        super.viewDidLoad()
        
    }
    
    override func setupNav() {
        
        navBgView.isHidden = true
    }
    
    override func setupTableView() {
        
        tableViewUseFrame = true
        
        tableViewPlain.frame = CGRectMake(0, JKNavBarHeight, JKScreenW, JKScreenH - JKNavBarHeight)
        
        tableViewPlain.rowHeight = 80
        tableViewPlain.contentInset = UIEdgeInsetsMake(0, 0, JKCurrentHomeIndicatorHeight, 0)
        tableViewPlain.backgroundColor = view.backgroundColor
        
        if #available(iOS 11.0, *) {
            
        } else {
            
            tableViewPlain.scrollIndicatorInsets = tableViewPlain.contentInset
        }
        
        tableViewPlain.showsHorizontalScrollIndicator = false
        tableViewPlain.showsVerticalScrollIndicator = false
        
        tableViewPlain.register(UINib(nibName: "JKNewsListCell", bundle: nil), forCellReuseIdentifier: "JKNewsListCell")
        
        tableViewPlain.mj_header = MJRefreshHeader(refreshingTarget: self, refreshingAction: #selector(loadNewData))
        tableViewPlain.addFooterWithRefreshingTarget(target: self, refreshingAction: #selector(loadMoreData))
        
        let tableHeader = UIView(frame: CGRect(x: 0, y: 0, width: JKScreenW, height: 30))
        tableViewPlain.tableHeaderView = tableHeader
        tableHeader.isHidden = true
        tableHeader.backgroundColor = view.backgroundColor
        
        // tableHeaderView上的label
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 15)
        label.text = "主编"
        label.sizeToFit()
        label.x = 15
        label.centerY = tableHeader.centerY
        tableHeader.addSubview(label)
        self.headerLabel = label
        
        // tableHeaderView右边的箭头
        let arrowImgV = UIImageView()
        arrowImgV.tag = 100
        arrowImgV.size = CGSizeMake(tableHeader.height, tableHeader.height)
        arrowImgV.x = JKScreenW - arrowImgV.width
        arrowImgV.centerY = label.centerY
        arrowImgV.image = UIImage(named: "Home_Arrow")
        tableHeader.addSubview(arrowImgV)
        
        // tableHeaderView底部分割线
        let separator = UIView()
        separator.tag = 21766
        separator.frame = CGRectMake(0, tableHeader.height - 1, tableHeader.width, 0.5)
        separator.backgroundColor = JKSameRGBColor(217)
        tableHeader.addSubview(separator)
        
        tableHeader.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapTableHeader)))
    }
    
    /** 计算导航标题宽度 */
    private func calculateTitleWidth() -> CGFloat {
        
        if themeModel == nil {
            return 0
        }
        
        if themeModel!.name == nil {
            return 0
        }
        
        let maxSize = CGSizeMake(CGFloat(MAXFLOAT), CGFloat(MAXFLOAT))
        
        return (themeModel!.name! as NSString).boundingRect(with: maxSize, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 18)], context: nil).size.width
    }
    
    // MARK: - 加载数据
    
    override func loadNewData() {
        
        if themeModel == nil {
            return
        }
        
        if themeModel!.id == nil {
            return
        }
        
        tableViewPlain.mj_footer.endRefreshing()
        refreshView.beginAnimating()
        tableViewPlain.mj_footer.isHidden = stories.count <= 0
        
        JKNetworkingTool.shared.requestGet(url: "theme/" + themeModel!.id!, parameters: nil) { (responseJson, error) in
            
            self.refreshView.stopAnimating()
            self.tableViewPlain.mj_header.endRefreshing()
            
            if error != nil {
                
                if self.stories.count > 0 { return }
                
                self.showReloadView()
                
                return
            }
            
            guard let json = responseJson as? [String : AnyObject] else {
                
                if self.stories.count > 0 { return }
                
                self.showReloadView()
                
                return
            }
            
            // 执行缓存
            JKSQLiteManager.cacheStoryLists(stories: json["stories"] as? [[String : AnyObject]], date: "0", isTop: false, isLatest: false, isMore: false)
            
            guard let contentModel = JKThemeContentModel.deserialize(from: json) else {
                
                if self.stories.count > 0 { return }
                
                self.showReloadView()
                
                return
            }
            
            self.hideReloadView()
            
            if self.stories.count > 0 && contentModel.stories != nil {
                
                if self.stories.first!.id == contentModel.stories!.first?.id {
                    return
                }
            }
            
            self.contentModel = contentModel
            self.stories = contentModel.stories ?? [JKNewsListModel]()
            self.editors = contentModel.editors ?? [JKThemeEditorModel]()
            
            DispatchQueue.main.afterMilliseconds(time: 250, block: {
                
                self.topImageView.alpha = 0
                
                self.topImageView.jk_setImage(withUrlStr: contentModel.image, placeHolder: nil, progressBlock: nil, completionHandler: { (image, error, imageURL) in
                    
                    if error != nil || image == nil { return }
                    
                    self.setBlurImage(originalImage: image!)
                    
                    UIView.animate(withDuration: 0.5, animations: {
                        
                        self.topImageView.alpha = 1
                    })
                })
            })
            
            if self.stories.count <= 0 { return }
            
            self.tableViewPlain.reloadData()
            self.tableViewPlain.mj_footer.isHidden = false
            
            // 循环添加主编头像
            for i in 0 ..< self.editors.count {
                
                let iconV = UIImageView()
                iconV.backgroundColor = nil
                iconV.size = CGSizeMake(18, 18)
                iconV.x = self.headerLabel!.frame.maxX + 12 + (20 + 5) * (CGFloat(i))
                iconV.centerY = self.tableViewPlain.tableHeaderView!.height * 0.5
                iconV.jk_setCircleIcon(withUrlStr: self.editors[i].avatar)
                //iconV.layer.cornerRadius = 9
                //iconV.layer.masksToBounds = true
                //iconV.kf.setImage(with: URL(string: self.editors[i].avatar ?? ""), placeholder: JKAccountManager.shared.headerIconPlaceHolder, options: [.transition(ImageTransition.fade(0.5))], progressBlock: nil, completionHandler: nil)
                
                self.tableViewPlain.tableHeaderView!.addSubview(iconV)
            }
            
            self.tableViewPlain.tableHeaderView?.isHidden = false
            
            self.tableViewPlain.backgroundColor = nil
        }
    }
    
    /** 设置模糊图片 */
    private func setBlurImage(originalImage: UIImage) {
        
        let context = CIContext(options: nil)
        
        //获取原始图片
        let inputImage =  CIImage(image: originalImage)
        
        //使用高斯模糊滤镜
        let filter = CIFilter(name: "CIGaussianBlur")!
        
        filter.setValue(inputImage, forKey:kCIInputImageKey)
        
        //设置模糊半径值（越大越模糊）
        filter.setValue(7, forKey: kCIInputRadiusKey)
        let outputCIImage = filter.outputImage!
        let rect = CGRect(origin: CGPoint.zero, size: originalImage.size)
        let cgImage = context.createCGImage(outputCIImage, from: rect)
        
        //显示生成的模糊图片
        topImageCoverView.image = UIImage(cgImage: cgImage!)
    }
    
    override func loadMoreData() {
        
        if self.stories.last!.id == nil {
            return
        }
        
        tableViewPlain.mj_header.endRefreshing()
        refreshView.beginAnimating()
        
        JKNetworkingTool.shared.requestGet(url: "theme/" + themeModel!.id! + "/before/" + self.stories.last!.id!, parameters: nil) { (responseJson, error) in
            
            self.refreshView.stopAnimating()
            self.tableViewPlain.mj_footer.endRefreshing()
            
            if error != nil {
                
                return
            }
            
            guard let json = responseJson as? [String : AnyObject] else {
                
                return
            }
            
            guard let stories = (json["stories"]) as? [[String : AnyObject]] else {
                
                return
            }
            
            // 执行缓存
            JKSQLiteManager.cacheStoryLists(stories: stories, date: "0", isTop: false, isLatest: false, isMore: false)
            
            guard let newsListModels = [JKNewsListModel].deserialize(from: stories) else {
                
                return
            }
            
            self.stories += (newsListModels as! [JKNewsListModel])
            
            self.tableViewPlain.reloadData()
        }
    }
    
    // MARK: - 点击事件
    
    override func navBackButtonClick() {
        
        let mainNav = navigationController as! JKMainNavigationController
        
        if mainNav.showLeftVcBlock != nil {
            
            mainNav.showLeftVcBlock!()
        }
    }
    
    @objc private func tapTableHeader() {
        
        let vc = JKThemeEditorsViewController()
        vc.editors = editors
        navigationController?.pushViewController(vc, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

// MARK: - tableView dataSource

extension JKBaseThemeViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return stories.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "JKNewsListCell") as? JKNewsListCell
        
        if cell == nil {
            
            cell = JKNewsListCell(style: UITableViewCellStyle.default, reuseIdentifier: "JKNewsListCell")
        }
        
        let model = stories[indexPath.row]
        
        model.alreadyRead = JKSQLiteManager.queryIsReadWithStoryID(storyID: model.id!)
        
        cell?.model = model
        
        return cell!
    }
}

// MARK: - tableView delegate

extension JKBaseThemeViewController {
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        super.tableView(tableView, didSelectRowAt: indexPath)
        
        let md = stories[indexPath.row]
        
        let vc = JKNewsDetailViewController()
        
        vc.storyID = md.id
        vc.themeStories = stories
        vc.stories = nil
        vc.indexPath = indexPath
        vc.storyListVc = self
        vc.backgroundImageUrl = contentModel?.background
        
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - scrollView delegate

extension JKBaseThemeViewController {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if (scrollView.contentOffset.y > 0) {
            
            self.refreshView.progress = 0
            self.topImageCoverView.alpha = 1
            
            return
        }
        
        self.topImageCoverView.alpha = scrollView.contentOffset.y / (self.topImageH - JKNavBarHeight) + 1
//        self.toolBar.alpha = self.topCoverImageView.alpha - 0.1
        
        // 刷新控件的进度
        self.refreshView.progress = -scrollView.contentOffset.y / 54.0
        
        topImageContainerViewView.y = -(self.topImageH - JKNavBarHeight) * 0.5 - scrollView.contentOffset.y * 0.5
        
        scrollView.contentOffset = (-scrollView.contentOffset.y >= (self.topImageH - JKNavBarHeight)) ? CGPointMake(0, -self.topImageH + JKNavBarHeight) : CGPointMake(0, scrollView.contentOffset.y)
    }
}

extension JKBaseThemeViewController: JKStoryListReadProtocol {
    
    func reloadReadStoryWith(indexPath: IndexPath?) {
        
        guard let _ = indexPath else { return }
        
        tableViewPlain.reloadRows(at: [indexPath!], with: UITableViewRowAnimation.none)
    }
}

extension JKBaseThemeViewController {
    
    override func updateSkin() {
        
        if vcSkinModel == currentSkinModel {
            return
        }
        
        super.updateSkin()
        
        tableViewPlain.tableHeaderView?.backgroundColor = view.backgroundColor
        self.headerLabel?.textColor = (currentSkinModel == JKDaySkinModelValue) ? JKSameRGBColor(96) : JKSameRGBColor(96)
        tableViewPlain.tableHeaderView?.viewWithTag(21766)?.backgroundColor = (currentSkinModel == JKDaySkinModelValue) ? JKSameRGBColor(217) : JKSameRGBColor(66)
        
        tableViewPlain.backgroundColor = stories.count > 0 ? nil : view.backgroundColor
    }
}
